package com.kkm.service.Imp;

import com.kkm.dao.Imp.TypeDaoImp;
import com.kkm.dao.TypeDao;
import com.kkm.pojo.PageBean;
import com.kkm.pojo.Type;
import com.kkm.service.TypeService;

import java.util.List;

public class TypeServiceImp implements TypeService {
    private TypeDao typeDao=new TypeDaoImp();
    @Override
    public PageBean<Type> showType(String currentPage , int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Type> pageBean=new PageBean(); //实例化pagebean对象
        int count=typeDao.checkCount();        //查询记录数

        int totalPage=count%rows==0?count/rows :count/rows+1;
        if(currPage>=totalPage){
            currPage=totalPage;
        }

        int index=(currPage-1)*rows;
        List<Type> types=typeDao.showType(index,rows);

        pageBean.setRows(rows);
        pageBean.setCurrentPage(currPage);
        pageBean.setTotalPage(totalPage);
        pageBean.setTotalCount(count);
        pageBean.setList(types);

        return pageBean;

    }

    @Override
    public int addType(String tname) {
        int num=0;
        num=typeDao.checkCount(tname);
        if(num==0){
            typeDao.addType(tname);
            return 1;
        }else {
            return 0;
        }
    }

    @Override
    public PageBean<Type> checkType(String checkName, String currentPage, int rows) {
        int currPage=Integer.parseInt(currentPage);
        if(currPage<=0){
            currPage=1;
        }
        PageBean<Type> pageBean=new PageBean(); //实例化pagebean对象
        int count=typeDao.checkCount(checkName);        //查询记录数
        if(count>=1){
            int totalPage=count%rows==0?count/rows :count/rows+1;
            if(currPage>=totalPage){
                currPage=totalPage;
            }

            int index=(currPage-1)*rows;
            List<Type> types=typeDao.checkType(checkName,index,rows);
            pageBean.setRows(rows);
            pageBean.setCurrentPage(currPage);
            pageBean.setTotalPage(totalPage);
            pageBean.setTotalCount(count);
            pageBean.setList(types);
            return pageBean;
        }
        return null;
    }

    @Override
    public void deleteType(String tid) {
        int id=Integer.parseInt(tid);
        typeDao.deleteType(id);
    }

    @Override
    public int modifyType(String tid, String newName) {
        int num=0;
        num=typeDao.checkCount(newName);
        if(num==0){
            int id=Integer.parseInt(tid);
            typeDao.modifyType(newName,id);
            return 1;
        }else {
            return 0;
        }
    }
}
